<template>
  <div class="setting-content inside-comment">
    <el-scrollbar height="calc(100vh - 170px)">
      <h2 class="setting-header">
        <strong>群组管理</strong>
      </h2>
      <div class="top-btns">
        <SearchCmp
          v-if="searchCmpArray.length"
          :searchCmpArray="searchCmpArray"
          :searchForm="queryData"
          @onSubmit="getTableData"
        />
        <el-button class="add-button" type="primary" @click="createGroup"
          >创建群组</el-button
        >
      </div>
      <RuifoxTable
        :loading="tableLoading"
        :table-data="tableData"
        :field-list="fieldList"
        :default-index="true"
        :default-checkbox="true"
      
      >
      <!-- :canDrag = "true"
      @handleSort="handleSort" -->
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox
              class="unmover"
              v-model="element.checked"
              @change="handleCheckTable(element.id)"
              size=""
            />
          </div>
        </template>

        <!-- 状态 -->
        <template #status="{ element }">
          <div>
            <el-tag v-if="element.status == 'UNSEALED'" type="primary"
              >未公开</el-tag
            >
            <el-tag v-if="element.status == 'NORMAL'" type="success"
              >正常</el-tag
            >
            <el-tag v-if="element.status == 'DISABLE'" type="info">禁用</el-tag>
          </div>
        </template>

        <!-- 开始时间列 -->
        <template #startTime="{ element }">
          {{ formatDate(element.startTime, "yyyy-MM-dd hh:mm") }}
        </template>

        <!-- 结束时间列 -->
        <template #endTime="{ element }">
          {{ formatDate(element.endTime, "yyyy-MM-dd hh:mm") }}
        </template>

        <!-- 考试时长列 -->
        <template #durationMinutes="{ element }">
          <span v-if="!element.durationMinutes">-</span>
        </template>

        <!-- 操作列 -->
        <template #options="{ element }">
          <div class="table-td-option unmover">
            <el-button type="primary" link @click="editGroup(element)"
              >编辑</el-button
            >
            <!-- <el-button type="primary" link @click="showGroup(element)"
              >查看成员</el-button
            > -->
            <el-button type="primary" link @click="delGroup(element)"
              >删除</el-button
            >
          </div>
        </template>
      </RuifoxTable>
      <PaginationView
        :isAffix="false"
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :options="batchOptions"
        :checkedNum="checkedNum"
        :canChoose="queryData.total > 0"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @invertChoose="handleInvertChoose"
        @checkOption="handleBatchOptions"
        @refreshList="getTableData"
        @cancelChoose="handleResetPagination"
        v-if="tableData.length > 0"
      />
      <!-- 添加群组  -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="400px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="群组名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入群组名称"/>
          </el-form-item>
          <el-form-item label="说明" prop="description">
            <el-input v-model="formData.description" placeholder="请输入群组说明" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="confirmGroup"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
      <!-- 群组成员  -->
      <el-dialog v-model="checkStudentDialog" title="群组成员" width="1100px">
        <CheckStudent />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showCourseInstance = false">取消</el-button>
            <el-button type="primary" @click="submitCheckStudent">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { formatDate } from "@/utils/tools";
import {
  saveGroup,
  pagingGroup,
  deleteGroup,
  getByIdGroup,
} from "@/api/group";
import { tableList as mixTable } from "@ruifox-cms/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import CheckStudent from '../components/CheckStudent.vue'


const searchCmpArray = ref([
  { label: "群组名称", key: "name" },
]);

const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: pagingGroup,
});
const defaultQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 10,
  sort: "",
  order: "",
  name: "",
  status: "",
  openType: "",
  businessKey: "",
  timeLimit: "",
  creator: "",
});

Object.assign(queryData, defaultQuery);

// const getTableData = async () => {
//   const res = await pagingGroup(queryData);
//   if (res.code === 20000) {
//     // oriTableData.value = res.data.records;
//     tableData.value = res.data.records;
//     queryData.total = res.data.total;
//     tableLoading.value = false
//   }
// };

const rules = { 
  name: [{ required: true, message: "请输入群组名称", trigger: "blur" }],
};

// 考试信息编辑
const dialogVisible = ref(false);
const dialogTitle = ref("");
const defaultFormData = reactive({
  id: "",
  name: "",
  description: ""
});
const formData = ref(defaultFormData);

//新增群组
const createGroup = () => {
  formData.value = { ...defaultFormData };
  dialogVisible.value = true;
  dialogTitle.value = "新增群组";
};

//编辑群组
const editGroup = async (item) => {
  const res = await getByIdGroup({ id: item.id });
  if (res.code === 20000) {
    dialogVisible.value = true;
    dialogTitle.value = "编辑群组";
    formData.value = res.data;
  }
};

//查看群组成员
// const checkStudentDialog = ref(false)
// const showGroup = async (item) => {
//   checkStudentDialog.value = true
//   console.log(item);
  
// };
//保存群组
const confirmGroup = async () => {
  if (formData.value.name === "") {
    ElMessage.warning("请输入群组名称");
    return;
  }
  const res = await saveGroup(formData.value);
  if (res.code === 20000) {
    ElMessage.success("保存成功");
    dialogVisible.value = false;
    getTableData();
  }
  formData.value = { ...defaultFormData };
};

//删除群组
const delGroup = async (item) => {
  ElMessageBox.confirm("确定删除该群组吗？", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await deleteGroup({ ids: item.id });
    if (res.code === 20000) {
      ElMessage.success("删除成功");
      getTableData();
    }
  });
};

// 批量删除
const handleBatchGroup = async () => {
  ElMessageBox.confirm("确定删除选中群组吗？", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let data = {
      ids: checkedList.value.join(','),
    };
    deleteGroup(data).then((res) => {
      if (res.code === 20000) {
        ElMessage.success("删除成功");
        getTableData();
        isAllChooseBtn.value = false;
        checkedList.value = [];
      }
    });
  });
}
const batchOptions = ref([
  { name: "删除", value: "delGroup", icon: "&#xe74b;" },
]);
const handleBatchOptions = (data) => {
  if (data === "delGroup") {
    handleBatchGroup();
  }  
};


// 拖拽排序
// const handleSort = async (e) => {
//   // 如果拖拽到了PageSort组件，则不触发排序
//   if (e.to.className.includes('page-sort-list')) {
//     return
//   }

//   let startSourceId, endSourceId, targetId
//   const movedContent = newTableData.value[e.newIndex]
//   // 如果是移动到最前面，或者目标位置前一条内容为置顶内容,且自身不是置顶内容时，则targetId为0
//   const previousIndex = e.newIndex - 1
//   if(previousIndex >= 0 && (!newTableData.value[previousIndex].is_top || (newTableData.value[previousIndex].is_top && movedContent.is_top))){
//     const previousContent = newTableData.value[previousIndex]
//     targetId = previousContent.id
//   } else {
//     targetId = 0
//   }
//   // 如果是批量移动，则取最小和最大排序值所对应元素的id
//   if (movedContent.isPageSort) {
//     startSourceId = Math.min(...movedContent.content.map(item => item.id))
//     endSourceId = Math.max(...movedContent.content.map(item => item.id))
//     // 然后展开数组插入到tableData中
//     newTableData.value.splice(e.newIndex, 1, ...movedContent.content)
//     pageSortRef.value.tableData = []
//   } else {
//     startSourceId = movedContent.id
//     endSourceId = movedContent.id
//   }
//   const data = {
//     catId: catId.value,
//     startSourceId,
//     endSourceId,
//     targetId
//   }
//   await updateSort(data)
//   handleSearch()
// }


const fieldList = ref([
  {
    title: "名称",
    name: "name",
  },
  {
    title: "说明",
    name: "description",
  },
  {
    title: "创建时间",
    name: "createdAt",
  },
  {
    title: "操作",
    name: "options",
    width: 200,
    fixed: "right",
  },
]);

onMounted(() => {
  getTableData();
});
</script>

<style scoped lang="scss">
.top-btns {
  display: flex;
  margin: 10px 0;
  justify-content: space-between;
  /* align-items: center; */
  .add-button {
    margin-right: 10px;
  }
}
::v-deep .el-step.is-simple .el-step__title {
  font-size: 14px;
}
.step-item {
  cursor: pointer;
}
.table-td-option {
  display: flex;
  align-items: center;
}
</style>
